import Taro from '@tarojs/taro-rn';
import * as tslib_1 from "tslib";
import React from 'react';
import { Component } from "@tarojs/taro-rn";
import { toJS } from 'mobx';
import { inject, observer } from "@tarojs/mobx-rn";
import { View, Image, Text, RichText, Swiper, SwiperItem, ScrollView } from "@tarojs/components-rn";
import { getRuntime, htmlToText, ServerHost } from "../../utils/common";
import custom_detailStyleSheet from "./custom_detail_styles";

import share from "../../assets/img/icon_46.png";
import right from "../../assets/img/right.png";
import close from "../../assets/img/close.png";
import share_icon from "../../assets/img/share_arrow.png";
import close_icon from "../../assets/img/icon_close_bold.png";
var _styleSheet = custom_detailStyleSheet;

function _getClassName() {
  var className = [];
  var args = arguments[0];
  var type = Object.prototype.toString.call(args).slice(8, -1).toLowerCase();

  if (type === 'string') {
    args = args.trim();
    args && className.push(args);
  } else if (type === 'array') {
    args.forEach(function (cls) {
      cls = _getClassName(cls).trim();
      cls && className.push(cls);
    });
  } else if (type === 'object') {
    for (var k in args) {
      k = k.trim();

      if (k && args.hasOwnProperty(k) && args[k]) {
        className.push(k);
      }
    }
  }

  return className.join(' ').trim();
}

function _getStyle(classNameExpression) {
  var className = _getClassName(classNameExpression);

  var classNameArr = className.split(/\s+/);
  var style = [];

  if (classNameArr.length === 1) {
    style.push(_styleSheet[classNameArr[0].trim()]);
  } else {
    classNameArr.forEach(function (cls) {
      style.push(_styleSheet[cls.trim()]);
    });
  }

  return style;
}

let MallDetail = class MallDetail extends Component {
  constructor(porps) {
    super(porps);

    this.getJsApiParam = () => {
      let currentUrl = window.location.href;
      let apiUrl = `${ServerHost}/api/Account/getWxJsApiParams?curUrl=${currentUrl}`;
      Taro.showLoading({ title: '加载中...' });
      fetch(apiUrl, {
        method: 'GET',
        mode: "cors",
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        credentials: 'same-origin'
      }).then(response => {
        Taro.hideLoading();
        return response.json();
      }).then(response => {
        let appId = response.appId;
        let timestamp = response.timestamp;
        let nonceStr = response.nonceStr;
        let signature = response.signature;
        this.setState({ wxConfig: response });
        wx.config({
          debug: false,
          appId: appId,
          timestamp: timestamp,
          nonceStr: nonceStr,
          signature: signature,
          // jsApiList: ['updateAppMessageShareData','onMenuShareAppMessage'], // 必填，需要使用的JS接口列表
          jsApiList: 'updateAppMessageShareData,onMenuShareTimeline,onMenuShareAppMessage,onMenuShareQQ,onMenuShareWeibo'.split(',')
        });
      }).catch(error => {
        console.log(error);
      });
    };

    this.state = {
      selectSpec: false,
      info: {},
      infoBanner: [],
      itemNum: 1,
      sku: [],
      selectedSku: [],
      specNoId: null,
      specObj: null,
      specStrArr: ['选择'],
      specNo: Array(),
      itemSpecs: [],
      isTips: false,
      tipsText: '',
      isShare: false
    };
  }
  componentWillMount() {
    Taro.setNavigationBarTitle({ title: '礼品定制详情' });
    let id = parseInt(this.$router.params.id);
    this.getJsApiParam();
    if (id) {
      this.getItemInfo(id);
    }
  }
  getItemInfo(id) {
    let { PointMallStore } = this.props.stores;
    PointMallStore.getItemInfo({
      formId: id,
      callback: res => {
        let resObj = toJS(res);
        let infoBanner = resObj.pictures.split(',');
        let sku = resObj.itemSkuCategories || [];
        //let sku =  this.state.sku
        // 初始化需要选择的规格
        let specStrArr = ['选择'];
        let specNo = Array(sku.length).fill(null);
        sku && sku.map((item, index) => {
          specStrArr.splice(index + 1, 1, item.name);
        });
        this.setState({
          info: resObj,
          infoBanner,
          sku,
          itemSpecs: res.itemSpecs,
          specStrArr,
          specNo
        }, () => {
          this.share();
        });
      }
    });
  }
  handelRouter(url = '/pages/index/index') {
    getRuntime().navigateTo(url);
  }
  // 打开规格弹窗
  selectSpec() {
    this.setState({
      selectSpec: !this.state.selectSpec
    });
  }
  // 关闭规格选择框
  closeSpec(e) {
    e.stopImmediatePropagation();
    this.setState({
      selectSpec: false
    }, () => {
      this.setStorage();
    });
  }
  // 点击规格选择时不会关闭弹出框
  openSpec(e) {
    e.stopPropagation();
    this.setState({
      selectSpec: true
    });
  }
  /**
   * 选择规格
   * @param column 选择的规格类别索引
   * @param id 选择的规格ID
   */
  selectOption(column, id) {
    let { specStrArr, specNo, itemSpecs } = this.state;
    let specStr = '';
    let specStrTemp = [];
    let specNoId = null;
    let specObj = null;
    // let specNoTemp = []
    specNo.splice(column, 1, id);
    // 更新规格显示字段spcStr
    let temp = specNo.filter(item => item);
    if (specNo.length === temp.length) {
      // 已选全部规格,匹配规格字符串得出价格
      itemSpecs.map(item => {
        if (item.specNo === specNo.join('-')) {
          specNoId = item.id;
          specObj = item;
        }
      });
    } else {
      // 还有未选规格
      specNo.map((item, index) => {
        if (item) {
          // 删除已选项
          specStrArr.splice(index + 1, 1);
        }
      });
    }
    this.setState({
      specStrArr,
      specNo,
      specNoId,
      specObj
    });
  }
  // 选择购买数量
  selectItemNum(type) {
    let { itemNum } = this.state;
    if (type === 'reduce') {
      // 减商品
      if (itemNum <= 1) {
        return;
      }
      itemNum--;
    } else {
      // 加商品
      itemNum++;
    }
    this.setState({
      itemNum
    }, () => {
      this.setStorage();
    });
  }
  // 缓存商品信息和所选规格信息
  setStorage() {
    let { info, itemNum, specNo, specNoId, specObj } = this.state;
    if (specNoId) {
      let cart = {
        itemId: info.id,
        name: info.name,
        picture: info.picture,
        freight: info.freight,
        publicDonations: info.publicDonations,
        pointValue: info.pointValue,
        specNo,
        itemNum,
        specNoId,
        itemSpec: specObj.spec,
        itemSignPrice: specObj.price,
        itemPrice: Math.round(specObj.price * itemNum * 100) / 100
      };
      getRuntime().setStorage('userCart', cart);
      // this.setCart(cart)
    } else {
      return;
    }
  }
  /**
   * @param data 缓存数据
   * @param type 缓存类型 add/reduce
   */
  setCart(data) {
    // debugger
    if (!data) return;
    let flag = false;
    // 存在商品ID修改，不存在增加
    let userCart = getRuntime().getStorage('userCart') || [];
    /*console.log('缓存值')
    console.log(userCart)*/
    userCart.map((item, index) => {
      if (item.itemId === data.itemId) {
        userCart.splice(index, 1, data);
        flag = true;
      }
    });
    if (!flag) {
      userCart.push(data);
    }
    getRuntime().setStorage('userCart', userCart);
  }
  // 购买按钮(下单)
  placeOrder(type = 1) {
    if (!getRuntime().getToken()) {
      getRuntime().navigateTo('/pages/login/login');
      return;
    }
    // 规格验证
    let { itemNum, specNoId, specObj } = this.state;
    let { PointMallStore } = this.props.stores;
    if (!specNoId && type === 2) {
      this.setState({ selectSpec: true });
      return;
    }
    if (!specNoId) {
      getRuntime().showToast('请选择规格~');
      return;
    }
    this.setStorage();
    /* PointMallStore.placeOrder({
       form: {
         itemSpecId: specNoId,
         qty: itemNum
       },
       callback: res => {
         console.log(res)
       }
     })*/
    getRuntime().navigateTo(`/pages/mall/order_confirm_custom?id=${this.state.info.id}&type=custom`);
  }
  share() {
    // if(!getRuntime().getToken()) { getRuntime().navigateTo('/pages/login/login'); return }
    let item = this.state.info;
    let url1 = ServerHost + '/m/#/pages/mall/custom_detail?id=' + item.id;
    let title = item.name;
    let desc = htmlToText(item.content);
    let imgUrl = item.picture;
    var shareData = {
      title,
      desc,
      imgUrl,
      otherImgUrl: '',
      url: window.location.href,
      link: window.location.href
    };
    wx.ready(function () {
      wx.onMenuShareTimeline(shareData);
      wx.updateAppMessageShareData(shareData);
      wx.onMenuShareQQ(shareData);
      wx.onMenuShareWeibo(shareData);
    });
  }
  btnShare() {
    this.setState({ isShare: true });
  }
  onClose() {
    this.setState({ isShare: false });
  }
  componentDidHide() {
    this.setState({ isShare: false });
  }
  render() {
    let { info, infoBanner, selectSpec, itemNum, sku, specObj, specStrArr, specNo, isShare } = this.state;
    let showSpecStr = specStrArr.join(' ');
    let totalPrice = '0.00';
    let specItemNum = 0;
    // console.log(specObj)
    // console.log(itemNum)
    if (specObj) {
      totalPrice = Math.round(specObj.price * itemNum * 100) / 100;
      specItemNum = itemNum;
    }
    return <View style={_styleSheet["mall-detail"]}>
        <View style={_styleSheet["swiper-wrap"]}>
          <Swiper indicatorColor="#fff" indicatorActiveColor="#00a0e9" circular indicatorDots autoplay={true} style={_styleSheet["swiper"]}>
            {infoBanner && infoBanner.map(item => {
            return <SwiperItem style={_styleSheet["swiper-item"]}>
                  <Image src={item} style={_styleSheet["swiper-img"]} />
                </SwiperItem>;
          })}
          </Swiper>
        </View>

        <View style={_styleSheet["share-info"]}>
          <View style={_styleSheet["line"]}>
            <View style={_styleSheet["title"]}>{info.name}</View>
            <View onClick={this.btnShare.bind(this)} style={_styleSheet["btn-share"]}>
              <Image src={share} style={_styleSheet["share-icon"]} />
              <Text style={_styleSheet["share-name"]}>分享</Text>
            </View>
          </View>
          <View style={[_styleSheet["line"], _styleSheet["line2"]]}>
            <View style={_styleSheet["price"]}>
              <Text style={_styleSheet["list-small"]}>￥</Text>
              <Text style={_styleSheet["list-price"]}>{info.price}</Text>
              <Text style={_styleSheet["list-old-price"]}>￥{info.originalPrice}</Text>
            </View>
            <View style={_styleSheet["all"]}>运费 <Text style={_styleSheet["count"]}>￥{info.freight}</Text></View>
          </View>
        </View>
        <View style={_styleSheet["interval"]} />

        <View onClick={this.selectSpec.bind(this)} style={_styleSheet["select-spec"]}>
          <View style={_styleSheet["title"]}>请选择规格数量</View>
          <View style={_styleSheet["drop-down-con"]}>
            <Text style={_styleSheet["con"]}>{itemNum}</Text>
            <Image src={right} style={_styleSheet["drop-down-icon"]} />
          </View>
        </View>
        <View style={_styleSheet["interval"]} />

        <View style={[_styleSheet["column-title"], _styleSheet["content-30"]]}>
          <Text style={_styleSheet["column-name"]}>商品详情</Text>
        </View>

        <View style={[_styleSheet["detail-info"], _styleSheet["rich-text"]]}>
          <RichText nodes={info.content} style={_styleSheet["rt"]} />
        </View>

        <View style={_styleSheet["footer-block"]} />
        <View style={_styleSheet["footer-block"]} />

        <View onClick={this.closeSpec.bind(this)} style={_getStyle(selectSpec ? 'spec-fixed  spec-fixed-active' : 'spec-fixed ')}>
          <View onClick={this.openSpec.bind(this)} style={_styleSheet["spec-content"]}>
            <View style={[_styleSheet["item"], _styleSheet["item1"]]}>
              <Image src={specObj ? specObj.picture : info.picture} style={_styleSheet["item1-img"]} />
              <View style={_styleSheet["info"]}>
                <View style={[_styleSheet["line"], _styleSheet["color"]]}>
                  <Text style={_styleSheet["list-small"]}>￥</Text>
                  <Text style={_styleSheet["list-price"]}>{specObj ? specObj.price : info.price}</Text>
                </View>
                <View style={_styleSheet["list-title"]}>
                  
                  {specObj ? specObj.spec : showSpecStr}
                </View>
              </View>
              <Image src={close} onClick={this.closeSpec.bind(this)} style={_styleSheet["btn-close"]} />
            </View>
            <ScrollView scrollY={true} style={_styleSheet["overflow"]}>
              {sku.length > 0 && sku.map((item, index) => {
              return <View key={item.id} style={[_styleSheet["item"], _styleSheet["item2"]]}>
                    <View style={[_styleSheet["spec-name"], _styleSheet["list-title"]]}>{item.name}</View>
                    <View style={_styleSheet["option"]}>
                      {item.itemSkus.map(option => {
                    return <Text key={option.id} onClick={this.selectOption.bind(this, index, option.id)} style={_getStyle(specNo[index] === option.id ? 'op op-active' : 'op')}>{option.sku}</Text>;
                  })}
                    </View>
                  </View>;
            })}
              <View style={[_styleSheet["item"], _styleSheet["buy-count"]]}>
                <View style={[_styleSheet["spec-count"], _styleSheet["list-title"]]}>购买数量</View>
                <View style={_styleSheet["spec-count-control"]}>
                  <View onClick={this.selectItemNum.bind(this, 'reduce')} style={_getStyle(itemNum < 2 ? 'btn reduce disabled' : 'btn reduce')}> - </View>
                  <Text style={[_styleSheet["btn"], _styleSheet["count"]]}> {itemNum} </Text>
                  
                  <View onClick={this.selectItemNum.bind(this, 'add')} style={[_styleSheet["btn"], _styleSheet["add"]]}> + </View>
                </View>
              </View>
            </ScrollView>
            <View onClick={this.placeOrder.bind(this, 1)} style={[_styleSheet["item"], _styleSheet["item4"]]}>
              <View style={_styleSheet["page-submit"]}>立即购买</View>
            </View>
          </View>
        </View>

        <View style={_styleSheet["page-footer2"]}>
          <View style={_styleSheet["all-price"]}>
            已选 <Text style={[_styleSheet["color"], _styleSheet["all-count"]]}>{specItemNum}</Text> 件商品，合计：
            <Text style={_styleSheet["color"]}> <Text style={_styleSheet["list-small"]}>￥</Text>{totalPrice}</Text>
          </View>
          <View onClick={this.placeOrder.bind(this, 2)} style={_styleSheet["btn-submit"]}>立即购买</View>
        </View>

        <View style={_getStyle(isShare ? 'share-arrow share-arrow-active' : 'share-arrow')}>
          <Image src={share_icon} style={_styleSheet["share-arrow-icon"]} />
          <View style={_styleSheet["con"]}>
            <View>请点击右上角</View>
            <View>通过【发送给朋友】</View>
            <View>分享给好友</View>
          </View>
          <Image onClick={this.onClose.bind(this)} src={close_icon} style={_styleSheet["close-icon"]} />
        </View>
      </View>;
  }
};
MallDetail = tslib_1.__decorate([inject("stores"), observer], MallDetail);
export default MallDetail;